package com.stella.ieproductivitybackend.service.impl;

import com.stella.ieproductivitybackend.entity.*;
import com.stella.ieproductivitybackend.entity.Progress;
import com.stella.ieproductivitybackend.mapper.HomeMapper;
import com.stella.ieproductivitybackend.service.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 首页服务层
 */
@Service
public class HomeServiceImpl implements HomeService {
    @Autowired
    private HomeMapper homeMapper;

    /**
     * 工厂列表
     */
    @Override
    public List<Factory> getFactoryList() {
        return homeMapper.getFactoryList();
    }

    /**
     * 品牌列表
     */
    @Override
    public List<Brand> getBrandList() {
        return homeMapper.getBrandList();
    }

    /**
     * 品牌类型
     */
    @Override
    public List<Brand> getBrandType() {
        return homeMapper.getBrandType();
    }

    /**
     * 型体数量
     */
    @Override
    public Integer getModelCount() {
        return homeMapper.getModelCount();
    }

    /**
     * 型体列表
     */
    @Override
    public List<Model> getModelList() {
        return homeMapper.getModelList();
    }

    /**
     * 搜索型体
     */
    @Override
    public List<Model> searchModel(String model) {
        return homeMapper.searchModel(model);
    }

    /**
     * 员工总数
     */
    @Override
    public Integer getEmployeeCount() {
        return homeMapper.getEmployeeCount() == null ? 0 : homeMapper.getEmployeeCount();
    }

    /**
     * 直间人工力其他数据
     */
    @Override
    public Map<String, Object> getEmployeeOther() {
        Map<String, Object> map = new HashMap<>();

        List<String> yearList = homeMapper.getEmployeeYear();
        List<String> monthList = homeMapper.getEmployeeMonth();
        List<String> factoryList = homeMapper.getEmployeeFactory();

        map.put("yearList", yearList);
        map.put("monthList", monthList);
        map.put("factoryList", factoryList);

        return map;
    }

    /**
     * 直间人工力详情
     */
    @Override
    public List<Employee> getEmployeeDetail(String year, String month, String factory) {
        List<Employee> list = homeMapper.getEmployeeDetail(year, month, factory);
        Employee total = homeMapper.getEmployeeTotal(year, month);

        if ("全厂".equals(factory) && list != null && total != null) {
            list.add(total);
        }

        return list;
    }

    /**
     * 纯粹达成率图表
     */
    @Override
    public Map<String, Object> getPureChart() {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<PureChart> pureChart = homeMapper.getPureChart();
        List<Integer> thisPureChart = new ArrayList<>();
        List<Integer> lastPureChart = new ArrayList<>();

        PureChart pureChart1 = homeMapper.getTargetPureChart();
        List<Integer> targetPureChart = new ArrayList<>();

        try {
            for (PureChart chart : pureChart) {
                for (Field field : chart.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(chart);
                    if (value != null) {
                        String str = value.toString();
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisPureChart.add(Integer.parseInt(str.substring(0, str.length() - 1)));
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastPureChart.add(Integer.parseInt(str.substring(0, str.length() - 1)));
                        }
                    } else {
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisPureChart.add(null);
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastPureChart.add(null);
                        }
                    }
                }
            }

            if (pureChart1 != null) {
                for (Field field : pureChart1.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(pureChart1);
                    if (value != null) {
                        String str = value.toString();
                        targetPureChart.add(Integer.valueOf(str));
                    } else {
                        targetPureChart.add(null);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        map.put("thisPureChart", thisPureChart);
        map.put("lastPureChart", lastPureChart);
        map.put("targetPureChart", targetPureChart);

        return map;
    }

    /**
     * 纯粹达成率详情
     */
    @Override
    public Map<String, List<Pure>> getPureDetail() {
        Map<String, List<Pure>> map = new LinkedHashMap<>();
        List<Pure> pureDetail = homeMapper.getPureDetail();

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "YY"};

        for (String m : month) {
            map.put(m, new ArrayList<>());
        }

        for (Pure pure : pureDetail) {
            map.get(pure.getMonth()).add(pure);
        }

        return map;
    }

    /**
     * 直间达成率图表
     */
    @Override
    public Map<String, Object> getDirectChart() {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<DirectChart> directChart = homeMapper.getDirectChart();
        List<Integer> thisDirectChart = new ArrayList<>();
        List<Integer> lastDirectChart = new ArrayList<>();

        DirectChart directChart1 = homeMapper.getTargetDirectChart();
        List<Integer> targetDirectChart = new ArrayList<>();

        try {
            for (DirectChart chart : directChart) {
                for (Field field : chart.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(chart);
                    if (value != null) {
                        String str = value.toString();
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisDirectChart.add(Integer.parseInt(str.substring(0, str.length() - 1)));
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastDirectChart.add(Integer.parseInt(str.substring(0, str.length() - 1)));
                        }
                    } else {
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisDirectChart.add(null);
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastDirectChart.add(null);
                        }
                    }
                }
            }

            if (directChart1 != null) {
                for (Field field : directChart1.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(directChart1);
                    if (value != null) {
                        String str = value.toString();
                        targetDirectChart.add(Integer.valueOf(str));
                    } else {
                        targetDirectChart.add(null);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        map.put("thisDirectChart", thisDirectChart);
        map.put("lastDirectChart", lastDirectChart);
        map.put("targetDirectChart", targetDirectChart);

        return map;
    }

    /**
     * 直间达成率详情
     */
    @Override
    public Map<String, List<Direct>> getDirectDetail() {
        Map<String, List<Direct>> map = new LinkedHashMap<>();
        List<Direct> directDetail = homeMapper.getDirectDetail();

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "YY"};

        for (String m : month) {
            map.put(m, new ArrayList<>());
        }

        for (Direct direct : directDetail) {
            map.get(direct.getMonth()).add(direct);
        }

        return map;
    }

    /**
     * 入库标准秒值图表
     */
    @Override
    public Map<String, Object> getWarehousingChart() {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<WarehousingChart> warehousingChart = homeMapper.getWarehousingChart();
        List<Integer> thisWarehousingChart = new ArrayList<>();
        List<Integer> lastWarehousingChart = new ArrayList<>();

        List<WarehousingChart> warehousingChart1 = homeMapper.getTargetWarehousingChart();
        List<Integer> targetWarehousingChart = new ArrayList<>();

        for (int i = 0; i < month.length; i++) {
            thisWarehousingChart.add(null);
            lastWarehousingChart.add(null);
            targetWarehousingChart.add(null);
        }

        for (WarehousingChart chart : warehousingChart) {
            if (Integer.parseInt(chart.getYear()) == year) {
                if ("YY".equals(chart.getMonth())) {
                    thisWarehousingChart.set(month.length - 1, chart.getTot_std_time2());
                } else {
                    thisWarehousingChart.set(Integer.parseInt(chart.getMonth()) - 1, chart.getTot_std_time2());
                }
            } else if (Integer.parseInt(chart.getYear()) == year - 1) {
                if ("YY".equals(chart.getMonth())) {
                    lastWarehousingChart.set(month.length - 1, chart.getTot_std_time2());
                } else {
                    lastWarehousingChart.set(Integer.parseInt(chart.getMonth()) - 1, chart.getTot_std_time2());
                }
            }
        }

        for (WarehousingChart chart : warehousingChart1) {
            if ("YY".equals(chart.getMonth())) {
                targetWarehousingChart.set(month.length - 1, chart.getTot_std_time2());
            } else {
                targetWarehousingChart.set(Integer.parseInt(chart.getMonth()) - 1, chart.getTot_std_time2());
            }
        }

        map.put("thisWarehousingChart", thisWarehousingChart);
        map.put("lastWarehousingChart", lastWarehousingChart);
        map.put("targetWarehousingChart", targetWarehousingChart);

        return map;
    }

    /**
     * 入库标准秒值其他数据
     */
    @Override
    public Map<String, Object> getWarehousingOther() {
        Map<String, Object> map = new HashMap<>();

        List<String> factoryList = homeMapper.getWarehousingFactory();
        List<String> yearList = homeMapper.getWarehousingYear();
        List<String> monthList = homeMapper.getWarehousingMonth();

        map.put("factoryList", factoryList);
        map.put("yearList", yearList);
        map.put("monthList", monthList);

        return map;
    }

    /**
     * 入库标准秒值详情
     */
    @Override
    public List<Warehousing> getWarehousingDetail(String year, String month) {
        return homeMapper.getWarehousingDetail(year, month);
    }

    /**
     * 入库标准秒值对比
     */
    @Override
    public List<Warehousing> getWarehousingCompare(String factory1, String year1, String month1, String factory2, String year2, String month2) {
        return homeMapper.getWarehousingCompare(factory1, year1, month1, factory2, year2, month2);
    }

    /**
     * 当月成型完工数量图表
     */
    @Override
    public CompletedChart getCompletedChart() {
        return homeMapper.getCompletedChart();
    }

    /**
     * 成型完工数量其它
     */
    @Override
    public Map<String, Object> getCompletedOther() {
        Map<String, Object> map = new HashMap<>();

        List<String> yearList = homeMapper.getCompletedYear();
        List<String> monthList = homeMapper.getCompletedMonth();

        map.put("yearList", yearList);
        map.put("monthList", monthList);

        return map;
    }

    /**
     * 成型完工数量详情
     */
    @Override
    public List<Completed> getCompletedDetail(String year, String month) {
        return homeMapper.getCompletedDetail(year, month);
    }

    /**
     * 当月新旧型体占比图表
     */
    @Override
    public ProportionChart getProportionChart() {
        return homeMapper.getProportionChart();
    }

    /**
     * 新旧型体占比其它
     */
    @Override
    public Map<String, Object> getProportionOther() {
        Map<String, Object> map = new HashMap<>();

        List<String> yearList = homeMapper.getProportionYear();
        List<String> monthList = homeMapper.getProportionMonth();

        map.put("yearList", yearList);
        map.put("monthList", monthList);

        return map;
    }

    /**
     * 新旧型体占比详情
     */
    @Override
    public List<Proportion> getProportionDetail(String year, String month) {
        return homeMapper.getProportionDetail(year, month);
    }

    /**
     * PPH 图表
     */
    @Override
    public Map<String, Object> getPPHChart() {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<PPHChart> pphChart = homeMapper.getPPHChart();
        List<Double> thisPPHChart = new ArrayList<>();
        List<Double> lastPPHChart = new ArrayList<>();

        PPHChart pphChart1 = homeMapper.getTargetPPHChart();
        List<Double> targetPPHChart = new ArrayList<>();

        try {
            for (PPHChart chart : pphChart) {
                for (Field field : chart.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(chart);
                    if (value != null) {
                        String str = value.toString();
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisPPHChart.add(Double.parseDouble(str));
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastPPHChart.add(Double.parseDouble(str));
                        }
                    } else {
                        if (Integer.parseInt(chart.getYear()) == year) {
                            thisPPHChart.add(null);
                        } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                            lastPPHChart.add(null);
                        }
                    }
                }
            }

            if (pphChart1 != null) {
                for (Field field : pphChart1.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    // 如果是 year 字段，直接跳过
                    if ("year".equals(field.getName())) {
                        continue;
                    }
                    Object value = field.get(pphChart1);
                    if (value != null) {
                        String str = value.toString();
                        targetPPHChart.add(Double.valueOf(str));
                    } else {
                        targetPPHChart.add(null);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        map.put("thisPPHChart", thisPPHChart);
        map.put("lastPPHChart", lastPPHChart);
        map.put("targetPPHChart", targetPPHChart);

        return map;
    }

    /**
     * PPH 详情
     */
    @Override
    public Map<String, List<PPH>> getPPHDetail() {
        Map<String, List<PPH>> map = new LinkedHashMap<>();
        List<PPH> pureDetail = homeMapper.getPPHDetail();

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "YY"};

        for (String m : month) {
            map.put(m, new ArrayList<>());
        }

        for (PPH pph : pureDetail) {
            map.get(pph.getMonth()).add(pph);
        }

        return map;
    }

    /**
     * 与核算进度达成图表
     */
    @Override
    public Map<String, Object> getProgressChart() {
        Map<String, Object> map = new HashMap<>();

        int year = Calendar.getInstance().get(Calendar.YEAR);

        String[] month = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "Total"};
        map.put("month", month);

        List<ProgressChart> progressChart = homeMapper.getProgressChart();
        List<Integer> thisProgressChart = new ArrayList<>();
        List<Integer> lastProgressChart = new ArrayList<>();

        int thisCount = 0;
        int lastCount = 0;
        int thisTotal = 0;
        int lastTotal = 0;

        for (int i = 0; i < 13; i++) {
            thisProgressChart.add(0);
            lastProgressChart.add(0);
        }

        for (ProgressChart chart : progressChart) {
            if (Integer.parseInt(chart.getYear()) == year) {
                thisProgressChart.set(Integer.parseInt(chart.getMonth()) - 1, chart.getRate());
            } else if (Integer.parseInt(chart.getYear()) == (year - 1)) {
                lastProgressChart.set(Integer.parseInt(chart.getMonth()) - 1, chart.getRate());
            }
        }

        for (int i = 0; i < 12; i++) {
            if (thisProgressChart.get(i) == 0) {
                thisProgressChart.set(i, null);
            } else {
                thisTotal += thisProgressChart.get(i);
                thisCount++;
            }

            if (lastProgressChart.get(i) == 0) {
                lastProgressChart.set(i, null);
            } else {
                lastTotal += lastProgressChart.get(i);
                lastCount++;
            }
        }

        if (thisCount > 0) {
            thisProgressChart.set(12, Math.round((float) thisTotal / (float) thisCount));
        } else {
            thisProgressChart.set(12, null);
        }

        if (lastCount > 0) {
            lastProgressChart.set(12, Math.round((float) lastTotal / (float) lastCount));
        } else {
            lastProgressChart.set(12, null);
        }

        map.put("thisProgressChart", thisProgressChart);
        map.put("lastProgressChart", lastProgressChart);

        return map;
    }

    /**
     * 与核算进度达成其它
     */
    @Override
    public Map<String, Object> getProgressOther() {
        Map<String, Object> map = new HashMap<>();

        List<String> yearList = homeMapper.getProgressYear();
        List<String> monthList = homeMapper.getProgressMonth();

        map.put("yearList", yearList);
        map.put("monthList", monthList);

        return map;
    }

    /**
     * 与核算进度达成详情
     */
    @Override
    public List<Progress> getProgressDetail(String year, String month) {
        return homeMapper.getProgressDetail(year, month);
    }
}
